<script setup>
import {RefreshLeft, Search} from "@element-plus/icons-vue";
import {onBeforeUnmount, onMounted, ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

const queryForm = ref({
  alertName: '',
  pageNum: 1,
  pageSize: 10,
  groupName: '',
  typeName: '',
  statusID: 2,
})

const total = ref(0)

const tableData = ref([])

const groupData = ref([])
const typeData = ref([])

const initLogsList = async () => {
  try {
    const res = await requestUtil.post('monitor_alert/alert/logs', queryForm.value)
    const data = res.data
    if (data.code === 200) {
      tableData.value = res.data.msg
      total.value = res.data.total
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}
initLogsList()

const initGroupAndTypeData = async () => {
  // 获取监控分组数据，和监控类型数据
  try {
    const res = await requestUtil.get('monitor_alert/group/action')
    const data = res.data
    if (data.code === 200) {
      groupData.value = data.group_msg
      typeData.value = data.type_msg
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}
initGroupAndTypeData()

const handleSizeChange = (pageSize) => {
  queryForm.value.pageNum = 1
  queryForm.value.pageSize = pageSize
  initLogsList()
}

const handleCurrentChange = (pageNum) => {
  queryForm.value.pageNum = pageNum
  initLogsList()
}

const formatDuration = (minutes) => {
  const days = Math.floor(minutes / 1440);
  const hours = Math.floor((minutes % 1440) / 60);
  const mins = minutes % 60;

  let result = '';
  if (days > 0) {
    result += `${days}天`;
  }
  if (hours > 0) {
    result += `${hours}小时`
  }
  if (mins > 0 || result === '') {
    result += `${mins}分钟`
  }
  return result
}
let timer = null;

onMounted(() => {
  // 每分钟执行一次，60000 毫秒 = 1 分钟
  timer = setInterval(initLogsList, 60000);
});
onBeforeUnmount(() => {
  // 离开页面时清除定时器
  if (timer) clearInterval(timer);
});

watch(
    () => queryForm.value.statusID,
    () => {
      initLogsList()
    }
)
</script>

<template>
  <div class="app-container">
    <el-card class="box-card">
      <template v-slot:header>
        <div class="space-between">
          <div>
            <el-text class="width-class">监控分组:</el-text>
            <el-select
                class="width-class"
                style="width: 150px"
                v-model="queryForm.groupName"
                placeholder="请选择"
                clearable
            >
              <el-option
                  v-for="item in groupData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
              />
            </el-select>

            <el-text class="width-class">监控类型:</el-text>
            <el-select
                class="width-class"
                style="width: 150px"
                v-model="queryForm.typeName"
                placeholder="请选择"
                clearable
            >
              <el-option
                  v-for="item in typeData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
              />
            </el-select>

            <el-text class="width-class">监控名称:</el-text>
            <el-input
                class="width-class"
                style="width: 150px"
                v-model="queryForm.alertName"
                placeholder="请输入监控名"
                clearable
            />
            <el-button type="primary" :icon="Search" @click="initLogsList()">搜索</el-button>
          </div>

          <div class="radio-container">
            <el-radio-group v-model="queryForm.statusID">
              <el-radio-button label="全部" value="2"/>
              <el-radio-button label="已恢复" value="1"/>
              <el-radio-button label="告警中" value="0"/>
            </el-radio-group>
            <el-button link @click="initLogsList()" class="btn-link">
              <template #icon>
                <RefreshLeft/>
              </template>
            </el-button>
          </div>
        </div>
      </template>


      <el-table :data="tableData"
                height="600px"
                stripe
                style="width: 100%"
      >
        <el-table-column prop="name__name" label="任务名" min-width="10%" align="center"/>
        <el-table-column prop="mon_group" label="监控分组" min-width="10%" align="center"/>
        <el-table-column prop="type" label="监控类型" min-width="5%" align="center"/>
        <el-table-column prop="mon_path" label="监控地址" min-width="20%" align="center"/>
        <el-table-column prop="alert_status" label="状态" min-width="5%" align="center">
          <template v-slot="scope">
            <span v-if="scope.row.alert_status === 0" class="el-tag el-tag--danger">告警中</span>
            <span v-else class="el-tag el-tag--success">已恢复</span>
          </template>
        </el-table-column>
        <el-table-column prop="recv_alert_group" label="接收告警组" min-width="10%" align="center"/>
        <el-table-column prop="duration_time" label="持续时间" min-width="10%" align="center">
          <template v-slot="scope">
            {{ formatDuration(scope.row.duration_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="first_alert_time" label="开始时间" min-width="10%" align="center"/>
      </el-table>
    </el-card>
  </div>
  <el-pagination
      :hide-on-single-page="true"
      v-model:currentPage="queryForm.pageNum"
      v-model:page-size="queryForm.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
</template>

<style scoped lang="scss">
.space-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 24px;

  .width-class {
    margin-right: 10px;
  }

  .radio-container {
    display: flex;
    justify-content: flex-end;

    .btn-link {
      margin-left: 20px;
      font-weight: bold;
      font-size: 26px;
    }
  }
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

:deep(th.el-table__cell) {
  word-break: break-word;
  color: var(--text-color);
  height: 40px;
  font-size: 13px;
}

.el-tag--small {
  margin-left: 5px;
}
</style>
